package com.xiyou.luckdraw.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.xiyou.luckdraw.common.result.ResponseData;
import com.xiyou.luckdraw.common.result.ResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: SecurityCheckController
 * @Description:
 * @author: limingxing
 * @Date: 2019-10-12 11:37
 */
@Api(tags = "违规内容校验")
@RequestMapping("/security")
@RestController
@Slf4j
public class SecurityCheckController {

    private static final String QQ_GET_ACCESS_TOKEN = "https://api.q.qq.com/api/getToken?grant_type=client_credential&appid=%s&secret=%s";
    private static final String QQ_MSGSECCHECK_URL = "https://api.q.qq.com/api/json/security/MsgSecCheck?access_token=%s";
   //    private static final String QQ_IMGSECCHECK_URL = "https://api.q.qq.com/api/json/security/ImgSecCheck?access_token=%s&appid=%s";
    private static final String QQ_IMGSECCHECK_URL = "https://api.q.qq.com/api/json/security/ImgSecCheck?access_token=%s";

//    private static final String appid = "1108815482";
//    private static final String secret = "QVhepeiOwIxwQeVL";
private static final String appid = "1109912276";
    private static final String secret = "9VHSn83kv2mzmPXJ";

    @ApiOperation(value = "QQ小程序校验内容")
    @PostMapping("/qq/msgSecCheck")
    public ResponseData qqMsgSecCheck(@RequestBody String content) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String accessToken = getAccessToken(httpclient);
        String result = "";
        if (StringUtils.isNotBlank(accessToken)) {
            try {
                HttpPost requestMsgCheck = new HttpPost(String.format(QQ_MSGSECCHECK_URL, accessToken));
                requestMsgCheck.addHeader("Content-Type", "application/json;charset=UTF-8");
                Map<String, String> paramMap = new HashMap<String, String>();
                paramMap.put("content", content);
                requestMsgCheck.setEntity(new StringEntity(JSONObject.toJSONString(paramMap), ContentType.create("application/json", "utf-8")));
                CloseableHttpResponse msgCheckResponse = httpclient.execute(requestMsgCheck);
                result = EntityUtils.toString(msgCheckResponse.getEntity(), "UTF-8");
                log.info("SecurityCheckController.qqMsgSecCheck result: {}", result);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        jsonObject.put("errcode", jsonObject.getString("errCode"));
        return new ResponseUtils().setData(jsonObject);
    }

    @ApiOperation(value = "QQ小程序校验图片")
    @PostMapping("/qq/imgSecCheck")
    public ResponseData qqImgSecCheck(MultipartFile multipartFile) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String accessToken = getAccessToken(httpclient);
        FileSystemResource resource = new FileSystemResource(multipartFile.getOriginalFilename());
        String url = "https://api.q.qq.com/api/json/security/ImgSecCheck?access_token=" + accessToken;
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("media", resource);
        RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
        RestTemplate restTemplate = restTemplateBuilder.build();
        Object result = restTemplate.postForObject(url, param, Object.class);
        System.out.println(result);
        /*if (StringUtils.isNotBlank(accessToken)) {
            try {
                HttpPost requestImgCheck = new HttpPost(String.format(QQ_IMGSECCHECK_URL, accessToken));        //appid+*
                requestImgCheck.addHeader("Content-Type", "application/octet-stream");
                InputStream inputStream = multipartFile.getInputStream();
                byte[] byt = new byte[inputStream.available()];
                inputStream.read(byt);
                requestImgCheck.setEntity(new ByteArrayEntity(byt, ContentType.create(multipartFile.getContentType())));
                CloseableHttpResponse ImgSecCheckResponse = httpclient.execute(requestImgCheck);
                String ImgSecCheckResult = EntityUtils.toString(ImgSecCheckResponse.getEntity(), "UTF-8");

                log.info("SecurityCheckController.qqImgSecCheck ImgSecCheckResult: {}", ImgSecCheckResult);
                return new ResponseUtils().setData(JSONObject.parseObject(ImgSecCheckResult));
            } catch (Exception e) {
                e.printStackTrace();//B7pH2R4g0Nl2dKjWLgZv-hUQj2NMksLa75UUWQ9Lxjzk7Ep240rfBhHuJ1NOLJbz1Qc
            }
        }*/
        return new ResponseUtils().setData(null);
    }


    /**
     * 根据loginType获取微信或者QQ的AccessToken
     *
     * @param httpclient
     * @return
     */
    private String getAccessToken(CloseableHttpClient httpclient) {
        try {
            HttpPost requestToken = new HttpPost(String.format(QQ_GET_ACCESS_TOKEN, appid, secret));

            requestToken.addHeader("Content-Type", "application/json;charset=UTF-8");
            CloseableHttpResponse responseToken = httpclient.execute(requestToken);
            String resultToken = EntityUtils.toString(responseToken.getEntity(), "UTF-8");// 转成string
            JSONObject jsonObject = JSONObject.parseObject(resultToken);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
